package archer.application.core.service.system;

import archer.application.core.entity.system.Menu;
import archer.application.core.entity.system.Role;
import archer.application.core.entity.system.RoleMenuRel;
import archer.framework.common.repository.condition.QueryCondition;
import archer.application.core.service.BaseService;
import archer.framework.protocol.result.ExecuteResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author christ
 * @date 2016/6/7
 */
@Service
@Transactional
public class MenuService extends BaseService {

    /**
     * 获得所有菜单
     *
     * @return
     */
    public ExecuteResult findList() {

        return success(Menu.find.query().orderBy("sort").findList());
    }

    /**
     * 新增/更新菜单
     *
     * @param menu
     * @return
     */
    public ExecuteResult store(Menu menu) {

        if (isEmpty(menu.getUrl())) {
            throwParamNullException("菜单url不能为空");
        }

        if (isEmpty(menu.getName())) {
            throwParamNullException("菜单名称不能为空");
        }

        if (isEmpty(menu.getSort())) {
            throwParamNullException("菜单排序号不能为空");
        }


        return success(menu.storeAndQuery());
    }


    /**
     * 删除菜单
     *
     * @param id
     * @return
     */
    public ExecuteResult delete(String id) {

        if (isEmpty(id)) {
            throwParamNullException("菜单不能为空");
        }

        //删除角色菜单的关联数据
        delete(RoleMenuRel.find
                .query()
                .where()
                .eq("menu.id", id)
                .findList());

        //删除主表数据
        new Menu().setId(id).logicalDelete();

        return success();

    }


    /**
     * 分页查询拥有该菜单的所有角色列表
     *
     * @param id
     * @param queryCondition
     * @return
     */
    public ExecuteResult findRoleList(String id, QueryCondition queryCondition) {

        if (isEmpty(id)) {
            throwParamNullException("菜单不能为空");
        }

        return success(findPagedList(Role.find
                        .query()
                        .where()
                        .eq("roleMenuRels.menu.id", id)
                        .query(), queryCondition)
        );
    }
}
